﻿using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using HYQY_Core.Entities.User;
using SqlSugar;

namespace HYQY_App.Tool.GenerateId
{
    /// <summary>
    /// 生成器
    /// </summary>
    public class GenerateIdService : IDynamicApiController, ISingleton, IGenerateIdService
    {
        /// <summary>
        /// 生成用户id自增锁
        /// </summary>
        private static readonly object _UserIdentity = new();

        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GenerateIdService(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 生成用户id
        /// </summary>
        /// <param name="useMan"></param>
        /// <returns></returns>
        public async Task<string> CreateUserId(string CreateMan)
        {
            int affectedRows;
            lock (_UserIdentity)
            {
                UserIdentity idPlatformUser = new()
                {
                    CreateMan = CreateMan,
                    CreateTime = DateTime.Now,
                };

                affectedRows = _db.Insertable(idPlatformUser).InsertColumns(it => new
                {
                    it.CreateMan,
                    it.CreateTime,
                }).ExecuteCommand();
            }

            if (affectedRows == 0)
            {
                throw Oops.Bah("用户Id生成错误");
            }

            var id = await _db.Queryable<UserIdentity>().MaxAsync(t => t.Id);

            return id.ToString();
        }
    }
}
